//
//  EQMainViewController.swift
//  EQQuestionBank
//
//  Created by 范伟健 on 2018/8/3.
//  Copyright © 2018年 FanWeiJian. All rights reserved.
//

import UIKit
import RxSwift
import HandyJSON

let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height

class EQMainViewController: UIViewController, EQNavigationBarProtocol {
    
    var slide : EQScrollCardView!
    var isLoading = false
    override func viewDidLoad() {
        super.viewDidLoad()
        AipOcrService.shard().auth(withAK: "M6584VsnnOBLft52iOUSIhNl", andSK: "uVkq0UHpb1QcICfcDFQbj8A5NXb1i8hA")
        self.setNavigationTitle(title: "青榄搜题", titleColor: .white)
        let nav = self.navigationBar()
        nav.backgroundColor = .clear
        setupUI()
        bindUI()
    }
    
    func setupUI(){
        let rect = CGRect(x: 20, y: kScreenH - 240 - 64, width: kScreenW - 40, height: 277)
        let ratioValue = (kScreenH - 118) / 450.0

        let slide = EQScrollCardView.init(frame: rect, zMargin: 9 / ratioValue, xMargin: 11 / ratioValue, alpha: 1000, angle: 2000)
        slide.backgroundColor = .clear
        self.slide = slide
        self.view.addSubview(slide)
    }
    
    func bindUI(){
        NotificationCenter.default.rx.notification(custom: .pushAnalysisVC).subscribe(onNext: { [weak self] (noti) in
            let model : EQQuestionModel! = noti.object as? EQQuestionModel
            if (model != nil) {
                let vc : EQAnalysisVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EQAnalysisVC") as! EQAnalysisVC
                vc.model = model
                self!.navigationController?.pushViewController(vc, animated: true)
            }
            }).disposed(by: rx.disposeBag)
    }
    

    @IBAction func clickCameraButton(_ sender: UIButton) {
        
        self.present(showAlertController, animated: true, completion: nil)
    }
    
    // MARK: 用于弹出选择的对话框界面
    var showAlertController: UIAlertController {
        let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        controller.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) // 取消按钮
        controller.addAction(UIAlertAction(title: "拍照选择", style: .default) { action in
            self.selectorSourceType(type: .camera)
        }) // 拍照选择
        controller.addAction(UIAlertAction(title: "相册选择", style: .default) { action in
            self.selectorSourceType(type: .photoLibrary)
        }) // 相册选择
        return controller
    }
    
    func selectorSourceType(type: UIImagePickerControllerSourceType) {
        let imagePicket = UIImagePickerController()
        imagePicket.delegate = self 
        imagePicket.sourceType = type
        // 打开图片选择器
        self.present(imagePicket, animated: true, completion: nil)
    }

}

extension EQMainViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image : UIImage! = info[UIImagePickerControllerOriginalImage]  as? UIImage
        // 拍照
        if picker.sourceType == .camera {
            //保存相册
//            UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImage(image:error:contextInfo:)), nil)
        }
        
        EQHUD.showWait()

        AipOcrService.shard().detectTextBasic(from: image, withOptions: ["language_type": "CHN_ENG","detect_direction":"true"], successHandler: { (res) in
            let json = res as? [ String :Any]
            print("==========json=========")
            print(json!)
            print("=======================")
            let ocrModel = EQOCRResultModel.deserialize(from: json)
            let text = ocrModel?.getText()
            if self.isLoading {return}
            self.isLoading = true
            print("--->问题:\(text!)")
            eqProvider.rx.request(.problemDistingguish(text: text!))
                .filterSuccessfulStatusAndRedirectCodes()
                .mapModel(EQResponseListModel<EQQuestionModel>.self)
                .subscribeOn(MainScheduler.instance)
                .subscribe(onSuccess: { (responseModel) in
                    
                    self.slide.setCardData(datas: responseModel.data!)
                    EQHUD.hidHUD()
                    self.isLoading = false
                }, onError: { (error) in
                    EQHUD.hidHUD()
                    EQHUD.showFail("未搜到题")
                    self.isLoading = false
                }).disposed(by: self.rx.disposeBag)
            
        }) { (error) in
            EQHUD.hidHUD()
            
        }
        picker.dismiss(animated: true, completion: nil)

    }
    
    @objc func saveImage(image:UIImage,error:NSError?,contextInfo:AnyObject) {
        
        if error != nil {
            print("保存失败")

        } else {
            
            print("保存成功")
        }
    }
}
